##########################################
## Copyright 2012-2013 Ceruti Francesco
##
##
## This file is part of LiSP (Linux Show Player).
##
## LiSP (Linux Show Player) is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## LiSP (Linux Show Player) is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with LiSP (Linux Show Player).  If not, see <http://www.gnu.org/licenses/>.
##########################################

from PyQt4 import QtGui, QtCore
from lisp.core.plugin import Plugin
from lisp.ui.preferences.preferences_widget import PreferencesWidget


class Shortcut(Plugin):

    PLUGIN_NAME = 'Shortcut'

    def __init__(self, main):
        super(Shortcut, self).__init__(main)

        self.collector = main.collector
        self.layout = main.collectorUi
        self.layout.getMediaWidgetClass().PREFERENCES_WIDGETS.append(ShortcutPreferences)

        self.map = {}

        self.collector.onMediaAdded.connect(self.connectMedia)

        self.layout.onKeyPressed.connect(self.onKeyPressed)

    def reset(self):
        self.map = {}

    def reload(self):
        self.reset()

        for media in self.collector.media:
            if(media.state != media.NONE):
                self.updateMap(media)

    def connectMedia(self, media):
        func = lambda: self.updateMap(media)
        media.onConfigurationChanged.connect(func)

    def updateMap(self, media):
        self.deleteFromMap(media)
        if('shortcut' in media.conf):
            if(media.conf['shortcut'] == ''):
                media.conf.pop('shortcut')
            else:
                if(media.conf['shortcut'] not in self.map):
                    self.map[media.conf['shortcut']] = []
                if(media not in self.map[media.conf['shortcut']]):
                    self.map[media.conf['shortcut']].append(media)

    def deleteFromMap(self, media):
        for key in self.map.keys():
            for m in self.map[key]:
                if(m == media):
                    self.map[key].remove(m)
                    return

    def onKeyPressed(self, keyEvent):
        key = keyEvent.text()
        if(key in self.map and key != ''):
            for media in self.map[key]:
                if(media.state == media.PLAYING):
                    if(media.conf['pause']):
                        media.pause()
                    else:
                        media.stop()
                elif(media.state == media.STOPPED or media.state == media.PAUSED):
                    media.play()


class ShortcutPreferences(PreferencesWidget):

    NAME = 'Shortcut'

    def __init__(self, size, parent=None):
        super(ShortcutPreferences, self).__init__(size, parent)

        self.verticalLayoutWidget = QtGui.QWidget(self)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 431, 100))
        self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setMargin(10)

        self.group = QtGui.QGroupBox(self.verticalLayoutWidget)

        self.horizontalLayoutWidget = QtGui.QWidget(self.group)
        self.horizontalLayoutWidget.setGeometry(0, 0, 400, self.group.height())
        self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)

        self.key = QtGui.QLineEdit(self.horizontalLayoutWidget)
        self.key.setMaxLength(1)
        self.horizontalLayout.addWidget(self.key)

        self.keyLabel = QtGui.QLabel('Shortcut', self.horizontalLayoutWidget)
        self.horizontalLayout.addWidget(self.keyLabel)

        self.horizontalLayout.addSpacing(250)

        self.verticalLayout.addWidget(self.group)

        self.warningLayoutWidget = QtGui.QWidget(self.verticalLayoutWidget)
        self.warningLayoutWidget.setGeometry(QtCore.QRect(40, 425, 390, 40))
        self.warningLayout = QtGui.QHBoxLayout(self.warningLayoutWidget)
        self.warningLayout.setMargin(0)

        self.warningLayout.addSpacing(10)

        self.warningImage = QtGui.QLabel(self.warningLayoutWidget)
        self.warningImage.setPixmap(QtGui.QIcon.fromTheme("dialog-warning").pixmap(QtCore.QSize(22, 22)))
        self.warningLayout.addWidget(self.warningImage)

        self.warning = QtGui.QLabel(self.warningLayoutWidget)
        self.warning.setText(" <b>Any hotkeys for the current layout does not work!</b>")
        self.warning.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed))
        self.warningLayout.addWidget(self.warning)

        self.verticalLayout.addWidget(self.warningLayoutWidget)

    def getConfiguration(self):
        return {'shortcut': self.key.text()}

    def setConfiguration(self, conf):
        if(conf is not None):
            if('shortcut' in conf):
                self.key.setText(conf['shortcut'])
